import tkinter as tk
import pickle
from datetime import datetime, timedelta
import os
home_dir = os.path.expanduser("~")
file_saved = os.path.join(home_dir, 'Documents', 'my_tasks', 'task_saved')
os.makedirs(os.path.dirname(file_saved), exist_ok=True)
try:
    with open(file_saved, 'rb') as f:
        task1 = pickle.load(f)
        print("Loaded tasks:", task1) 
except (FileNotFoundError, pickle.UnpicklingError, EOFError, ValueError) as e:
    task1 = []
    print(f"Failed to load the saved file: {e}")

window = tk.Tk()
window.config(bg='#FFFFE0')
window.title('CBM记事本')
lable2 = tk.Label(window, text='请输入您的计划/Please add your plan:')
lable2.config(bg='#F5F5F5')
lable2.pack()
entry1 = tk.Entry(window)
entry1.pack()
lable3 = tk.Label(window, text='输入截止日期/date (deadline in YYYY-MM-DD HH:MM):')
lable3.pack()
entry2 = tk.Entry(window)
entry2.pack()
priority_stuff = tk.StringVar()
priority_stuff.set('最首要任务/High')
priority_menu = tk.OptionMenu(window, priority_stuff, "最首要任务/High", "首要任务/Medium", "次要任务/Low")
priority_menu.pack()
frame = tk.Frame(window)
frame.pack(fill=tk.BOTH, expand=True)
note = tk.Listbox(frame)
note.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
scrollbar_y = tk.Scrollbar(frame, command=note.yview)
scrollbar_y.pack(side=tk.RIGHT, fill=tk.Y)
note.config(yscrollcommand=scrollbar_y.set)
scrollbar_x = tk.Scrollbar(frame, orient=tk.HORIZONTAL, command=note.xview)
scrollbar_x.pack(side=tk.BOTTOM, fill=tk.X)
note.config(xscrollcommand=scrollbar_x.set)
def update_task_list():
    note.delete(0, tk.END)
    data1 = datetime.now()
    for task, priority, set_time1 in task1:
        color = "#8B0000" if priority == "最首要任务/High" else '#FFA500' if priority == "首要任务/Medium" else '#00008B'
        if set_time1 and data1 >= set_time1:
            color = "#333333"
        note.insert(tk.END, f"[{priority}] {task} - {set_time1.strftime('%Y-%m-%d %H:%M')}")
        note.itemconfig(note.size() - 1, {'fg': color})

def cut_piece():
    cut1 = note.curselection()
    if not cut1:
        return
    for index in reversed(cut1):
        cut2 = note.get(index)
        note.delete(index)
        for i, (task, priority, set_time1) in enumerate(task1):
            task_list = f"[{priority}] {task} - {set_time1.strftime('%Y-%m-%d %H:%M')}"
            if task_list == cut2:
                task1.pop(i)
                break
    update_task_list()
    with open(file_saved, 'wb') as f:
        pickle.dump(task1, f)
def button_click():
    task2 = entry1.get()
    set_time = entry2.get()
    prior = priority_stuff.get()
    try:
        set_time1 = datetime.strptime(set_time, '%Y-%m-%d %H:%M')
        task1.append((task2, prior, set_time1))
        update_task_list()
        entry1.delete(0, tk.END)
        entry2.delete(0, tk.END)
        with open(file_saved, 'wb') as f:
            pickle.dump(task1, f)
    except ValueError:
        print("无效的截止日期,请使用YYYY-MM-DD HH:MM")
button1 = tk.Button(text='保存/Save', command=button_click)
button1.pack()
button2 = tk.Button(window, text='删除/Delete', command=cut_piece)
button2.pack()
window.geometry("400x600")
window.resizable(False, False)
update_task_list()
def update_list():
    update_task_list()
    window.after(5000, update_list)
update_list()
window.mainloop()